package com.hyfd.deal.Flow;

import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.hyfd.common.GenerateData;
import com.hyfd.common.utils.Base64;
import com.hyfd.common.utils.MapUtils;
import com.hyfd.common.utils.PostUtil;
import com.hyfd.common.utils.Sign;
import com.hyfd.common.utils.ToolDateTime;
import com.hyfd.common.utils.ToolHttp;
import com.hyfd.common.utils.XmlUtils;
import com.hyfd.deal.BaseDeal;

/**
 * Create Date: 2017年8月31日 下午2:45:42
 * 
 * @version: V3.0.0
 * @author: zj
 */
public class JingRunYuanFlowDeal implements BaseDeal
{
    Logger log = Logger.getLogger(getClass());
    
    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> deal(Map<String, Object> order)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        int flag = -1;
        
        try
        {
            // 手机号
            String phoneNumber = (String)order.get("phone");
            
            Map<String, Object> channel = (Map<String, Object>)order.get("channel");// 获取通道参数
            String linkUrl = (String)channel.get("link_url");// 充值地址
            String defaultParameter = (String)channel.get("default_parameter");// 默认参数
            Map<String, String> paramMap = XmlUtils.readXmlToMap(defaultParameter);
            String account = paramMap.get("account"); // 渠道商编号 
            String key = paramMap.get("key");// 密钥
            
            String timeStamp= ToolDateTime.format(new Date(), "yyyyMMddHHmmss");
            // 平台订单号
            String curid = account+","+timeStamp;
            String curids = Base64.encodeBytes(curid.getBytes());
            String orderId =
                    ToolDateTime.format(new Date(), "yyyyMMddHHmmssSSS") + phoneNumber + GenerateData.getIntData(9, 2);
            
            map.put("orderId", orderId);
            	
            //签名串
            String signature = sign(key, timeStamp, account);
            
//            String spec = new Double(order.get("value") + "").intValue() + ""; // 流量包大小
            String productId = (String)order.get("providerProductId");//产品id
            
            linkUrl = linkUrl + "?mobile=" + phoneNumber + "&productCode=" + productId + "&nonce=" + curids 
            		+ "&signature=" + signature + "&otherParam="+orderId;
            
    		String retMsg = ToolHttp.get(false, linkUrl);
            
            // 判断是否成功
    		if(retMsg != null){
    			Map<String,String> resultMap = new HashMap<String, String>();
    			resultMap = (Map<String, String>) JSONObject.parse(retMsg);
    			
    			String channelOrderId = resultMap.get("orderNo");
    			map.put("providerOrderId", channelOrderId);
    			String result = resultMap.get("status");
    			if("00000".equals(result) || "00002".equals(result)){// 提交成功
    				flag = 1;
    				map.put("resultCode", result+":提交成功");
    			}else{//提交失败
					flag = 0;
					map.put("resultCode", result+":提交失败");
				}
    			
    		}
        }
        catch (ConnectTimeoutException | SocketTimeoutException e)
        {// 请求、响应超时
            flag = -1;
        }
        catch (Exception e)
        {
            log.error("晶润源流量出错" + e + MapUtils.toString(order));
        }
        map.put("status", flag);
        return map;
    }
    
    /**
    *@param key 接入密钥
    *@param timestamp 时间戳
    *@param account客户账户
    *@return 加密后的签名值
    */
    public static String sign (String key, String timestamp, String account) {
       String[] arr = new String[]{key, timestamp, account };
       Arrays.sort(arr);
       StringBuilder content = new StringBuilder();
       for (int i = 0; i < arr.length; i++) {
          content.append(arr[i]);
       }
       String signature = null;
       try {
          MessageDigest md = MessageDigest.getInstance("SHA-1");
          byte[] digest = md.digest(content.toString().getBytes("utf-8"));
          signature =toHexString(digest);
       } catch (NoSuchAlgorithmException e) {
          e.printStackTrace();
       } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
       }
       return signature;
    }

    public static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
    public static String toHexString(byte[] bytes) {
       StringBuilder sb = new StringBuilder(bytes.length * 2);
       for (int i = 0; i < bytes.length; i++) {
          sb.append(HEX_DIGITS[(bytes[i] & 0xf0) >>> 4]);
          sb.append(HEX_DIGITS[bytes[i] & 0x0f]);
       }
       return sb.toString();
    }

    public static void main(String[] args) {
    	String curids = "account,2016013015555";
        String curidss = Base64.encodeBytes(curids.getBytes());
		System.out.println("proiductId="+curidss);
		
	}
}
